from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from carts.utils import merge_cookie_redis_cart
from mall import settings
from oauth.serializers import OAuthWeiboUserSerializer
from oauth.sinaweibopy3 import APIClient
from oauth.utils import generate_sign_openid
from .models import OAuthQQUser, OAuthWeiboUser
from . import serializers

class OAuthQQLoginView(APIView):
    def get(self,request):
        #1,获取参数
        state = request.query_params.get("state","/")

        #2,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state=state)

        #3,返回qq登陆页面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url":login_url})

class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    def get(self,request):
        #1,获取参数code,校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        #2,根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state="/")
        access_token = oauth_qq.get_access_token(code)


        #3,根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)

        #4,通过openid查询qq对象用户
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #4,1初次授权
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token":sign_openid})
        else:
            #5,非初次授权
            user = oauth_qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            #合并购物车,返回
            response = Response({
                "token":token,
                "username":user.username,
                "user_id":user.id
            })
            response = merge_cookie_redis_cart(request, user, response)
            return response

    def post(self,request):
        #1,获取参数
        dict_data = request.data

        #2,创建序列化器
        serializer = self.get_serializer(data=dict_data)

        #3,校验,入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        #3,1根据用户数据,生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并购物车,返回
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })

        response = merge_cookie_redis_cart(request, user, response)

        return response

class OAuthWeiboLoginView(APIView):
    """获取url地址"""
    def get(self, request):

        # 获取前端传入的参数
        state = request.query_params.get('next')
        if not state:
            state = '/'
        # 实例化对象
        api = APIClient(app_key=settings.WEIBO_CLIENT_ID,
        app_secret=settings.WEIBO_CLIENT_SECRET,
        redirect_uri=settings.WEIBO_REDIRECT_URI)
        # 获取url
        login_url = api.get_authorize_url()

        return Response({'login_url': login_url})


class OauthWeiboView(APIView):

    def get(self, request):
        # 1、获取code值
        code = request.query_params.get('code', None)
        # 2、判断code是否传递过来
        if not code:
            return Response({'errors': '缺少code值'}, status=400)
        # 实例化对象
        api = APIClient(app_key=settings.WEIBO_CLIENT_ID, app_secret=settings.WEIBO_CLIENT_SECRET,redirect_uri=settings.WEIBO_REDIRECT_URI)
        try:
            res_data = api.request_access_token(code)
            access_token = res_data.get('access_token')
        except Exception as e:
            return Response({'message': 'weibo服务器异常'}, status=400)
        # try:
        #     pass
        # except:
        #     return Response({'message': '服务器错误'})
        # 判断数据表是否存在该access_token,存在表示绑定了 ,没有表示未绑定
        try:
            sina = OAuthWeiboUser.objects.get(access_token=access_token)
        except:

            tjs_token = generate_sign_openid(access_token)
            return Response({'access_token': tjs_token})
        else:
            # 如果绑定了,返回user_id,username,token
            user = sina.user
            # 手动签发JWT
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })

            response = merge_cookie_redis_cart(request, user, response)

            return response

    def post(self,request):
        #1,获取参数
        dict_data = request.data

        #2,创建序列化器
        serializer = OAuthWeiboUserSerializer(data=dict_data)

        #3,校验,入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        #3,1根据用户数据,生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })
        # 合并购物车,返回
        response = merge_cookie_redis_cart(request, user, response)

        return response

    